package com.tsmti.core.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.tsmti.core.common.annotation.RequiresMethodPermissions;
import com.tsmti.core.common.annotation.SameUrlData;
import com.tsmti.core.common.constant.Constants;
import com.tsmti.core.common.data.DuplicateValid;
import com.tsmti.core.common.entity.AbstractEntity;
import com.tsmti.core.common.entity.TreeNode;
import com.tsmti.core.common.entity.TreeNodeHelper;
import com.tsmti.core.common.model.AjaxJson;
import com.tsmti.core.common.model.ValidJson;
import com.tsmti.core.common.query.annotation.PageableDefaults;
import com.tsmti.core.common.query.data.*;
import com.tsmti.core.common.service.BaseService;
import com.tsmti.core.util.*;
import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title：PimsSystem
 * Class：com.tsmti.core.common.controller
 * Comapny:
 *
 * @author：zcw
 * @version：2.5 CreateTime：2018/1/16 14:57
 * Modify log:
 * Description：
 */
public abstract class BaseCrudController<Entity extends AbstractEntity<ID>, ID extends Serializable> extends BaseController {
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 实体类型
     */
    protected final Class<Entity> entityClass;

    @Autowired
    protected BaseService<Entity> baseService;

    public Entity get(ID id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return baseService.get(id);
        } else {
            return newModel();
        }
    }

    protected BaseCrudController() {
        this.entityClass = ReflectionUtils.getSuperGenericType(getClass());
    }

    protected Entity newModel() {
        try {
            return entityClass.newInstance();
        } catch (Exception e) {
            throw new IllegalStateException("can not instantiated model : " + this.entityClass, e);
        }
    }

    /**
     * list 运行之前
     *
     * @param model
     * @param request
     * @param response
     */
    public void preList(Model model, HttpServletRequest request, HttpServletResponse response) {
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        preList(model, request, response);
        return display("list");
    }

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "ajaxTreeList", method = RequestMethod.GET)
    private void ajaxTreeList(Queryable queryable,
                              @RequestParam(value = "nodeid", required = false, defaultValue = "") Long nodeid,
                              @RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
                              HttpServletRequest request, HttpServletResponse response, PropertyPreFilterable propertyPreFilterable)
            throws IOException {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        preAjaxList(queryable, detachedCriteria, request, response);
        List<Entity> treeNodeList = null;
        // 非异步
        if (!async) {
            treeNodeList = baseService.listWithNoPage(queryable, detachedCriteria);
            TreeSortUtils.create().sort(treeNodeList).async(treeNodeList);
        } else {
            // 异步模式只查自己
            if (ObjectUtils.isNullOrEmpty(nodeid)) {
                // 判断的应该是多个OR条件
                detachedCriteria.add(Restrictions.isNull("parentId"));
            } else {
                detachedCriteria.add(Restrictions.eq("parentId", nodeid));
            }
            treeNodeList = baseService.listWithNoPage(queryable, detachedCriteria);
            TreeSortUtils.create().sync(treeNodeList);
        }
        propertyPreFilterable.addQueryProperty("id", "expanded", "hasChildren", "leaf", "loaded", "level", "parentId");
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Entity> pagejson = new PageJson<Entity>(treeNodeList);
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "getTreeData")
    private void getTreeData(Queryable queryable, @RequestParam(value = "nodeid", required = false, defaultValue = "") Long nodeid, HttpServletRequest request,
                             HttpServletResponse response, PropertyPreFilterable propertyPreFilterable) throws IOException {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        List<Entity> treeNodeList = baseService.listWithNoPage(queryable, detachedCriteria);
        List<TreeNode> treeNodes = TreeNodeHelper.create().sort(treeNodeList);
        propertyPreFilterable.addQueryProperty("text", "href", "tags", "nodes");
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        String content = JSON.toJSONString(treeNodes, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "treeData")
    public void treeData(Queryable queryable,
                         @RequestParam(value = "nodeid", required = false, defaultValue = "") ID nodeid,
                         @RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        List<Entity> treeNodeList = null;
        if (!async) {
            // 非异步 查自己和子子孙孙
            treeNodeList = baseService.listWithNoPage(queryable, detachedCriteria);
            TreeSortUtils.create().sort(treeNodeList).async(treeNodeList);
        } else {
            // 异步模式只查自己
            if (ObjectUtils.isNullOrEmpty(nodeid)) {
                // 判断的应该是多个OR条件
                detachedCriteria.add(Restrictions.isNull("parentId"));
            } else {
                detachedCriteria.add(Restrictions.eq("parentId", nodeid));
            }
            treeNodeList = baseService.listWithNoPage(queryable, detachedCriteria);
            TreeSortUtils.create().sync(treeNodeList);
        }
        PropertyPreFilterable propertyPreFilterable = new QueryPropertyPreFilter();
        propertyPreFilterable.addQueryProperty("id", "name", "expanded", "hasChildren", "leaf", "loaded", "level",
                "parentId");
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Entity> pagejson = new PageJson<Entity>(treeNodeList);
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "ajaxList", method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")
    public void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                         HttpServletResponse response) throws IOException {

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        queryable.addCondition("delFlag", "0");
        preAjaxList(queryable, detachedCriteria, request, response);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Entity> pageJson = new PageJson<Entity>(baseService.list(queryable, detachedCriteria));
        String content = JSON.toJSONString(pageJson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 动态加载自己组装数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "ajaxCustomList", method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")
    @ResponseBody
    public DataResponse ajaxCustomList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        DataResponse dataResponse = new DataResponse();
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        preAjaxList(queryable, detachedCriteria, request, response);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Entity> pagejson = new PageJson<Entity>(baseService.list(queryable, detachedCriteria));
        dataResponse.setRows(getResultMap(pagejson.getResults()));
        response.setContentType("text/html; charset=UTF-8");
        return dataResponse;
    }


    /**
     * 取数前操作
     *
     * @param queryable
     * @param detachedCriteria
     * @param request
     * @param response
     */
    public void preAjaxList(Queryable queryable, DetachedCriteria detachedCriteria, HttpServletRequest request,
                            HttpServletResponse response) {

    }


    public String showView(Entity entity, Model model, HttpServletRequest request, HttpServletResponse response) {
        return "";
    }

    /**
     * @param model
     * @param id
     * @param request
     * @param response
     * @return
     * @title: _view
     * @description: 查看
     * @return: String
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String _view(Model model, @PathVariable("id") ID id, HttpServletRequest request,
                        HttpServletResponse response) {
        Entity entity = get(id);
        showUpdate(entity, model, request, response);
        model.addAttribute("data", entity);
        String showView = showView(newModel(), model, request, response);
        if (!StringUtils.isEmpty(showView)) {
            return display(showView);
        }
        return display("edit");
    }

    public void preEdit(Entity entity, Model model, HttpServletRequest request, HttpServletResponse response) {

    }

    public String showCreate(Entity entity, Model model, HttpServletRequest request, HttpServletResponse response) {
        return "";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String _showCreate(Model model, HttpServletRequest request, HttpServletResponse response) {
        preEdit(newModel(), model, request, response);
        String creteaView = showCreate(newModel(), model, request, response);
        if (!model.containsAttribute(Constants.DATA)) {
            model.addAttribute(Constants.DATA, newModel());
        }
        if (!StringUtils.isEmpty(creteaView)) {
            return creteaView;
        }
        return display("edit");
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") Entity entity, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(entity, request, response, result);
    }

    public String showUpdate(Entity entity, Model model, HttpServletRequest request, HttpServletResponse response) {
        return "";
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String _showUpdate(@PathVariable("id") ID id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        Entity entity = get(id);
        preEdit(entity, model, request, response);
        model.addAttribute("data", entity);
        String updateView = showUpdate(newModel(), model, request, response);
        if (!StringUtils.isEmpty(updateView)) {
            return updateView;
        }
        return display("edit");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") Entity entity, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(entity, request, response, result);
    }

    /**
     * 保存数据之前
     *
     * @param entity
     * @param request
     * @param response
     */
    public void preSave(Entity entity, HttpServletRequest request, HttpServletResponse response) {
    }

    /**
     * 判断数据是否重复
     * @param entity
     * @return
     */
    public boolean isRepeat(Entity entity){
        return false;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @SameUrlData
    @ResponseBody
    public AjaxJson doSave(Entity entity, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = AjaxJson.success();
        if (hasError(entity, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson = AjaxJson.fail(errorMsg);
            } else {
                ajaxJson = AjaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        if(isRepeat(entity)){
            return AjaxJson.fail("已存在重复数据!");
        }
        try {
            preSave(entity, request, response);
            if (ObjectUtils.isNullOrEmpty(entity.getId())) {
                entity = baseService.save(entity);
            } else {
                // FORM NULL不更新
                Entity oldEntity = baseService.get(entity.getId());
                BeanUtils.copyBeanNotNull2Bean(entity, oldEntity);
                baseService.update(oldEntity);
            }
            afterSave(entity, request, response);
            loadCache();
        } catch (Exception e) {
            logger.error("保存失败", e);
            ajaxJson = AjaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    /**
     * 保存数据之后
     *
     * @param entity
     * @param request
     * @param response
     */
    public void afterSave(Entity entity, HttpServletRequest request, HttpServletResponse response) {

    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") ID id) {

        AjaxJson ajaxJson = AjaxJson.success("删除成功");
        try {
            baseService.removeById(id);
            loadCache();
        } catch (Exception e) {
            logger.error("删除失败", e);
            ajaxJson = AjaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) ID[] ids) {
        AjaxJson ajaxJson = AjaxJson.success(0, "删除成功", null);
        try {
            List<ID> idList = java.util.Arrays.asList(ids);
            baseService.removeAllById(idList);
            loadCache();
        } catch (Exception e) {
            logger.error("删除失败", e);
            ajaxJson = AjaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    /**
     * 重载缓存
     */
    public void loadCache(){

    }


    /**
     * 共享的验证规则 验证失败返回true
     *
     * @param entity
     * @param result
     * @return
     */
    protected boolean hasError(Entity entity, BindingResult result) {
        Assert.notNull(entity, "entity is required");
        return result.hasErrors();
    }

    /**
     * @param result
     * @return
     * @title: errorMsg
     * @description: 错误信息组装
     * @return: String
     */
    protected String errorMsg(BindingResult result) {
        StringBuilder errorMsg = new StringBuilder("");
        if (result.getErrorCount() > 0) {
            List<ObjectError> objectErrorList = result.getAllErrors();
            for (ObjectError objectError : objectErrorList) {
                String message = MessageUtils.getMessage(objectError.getCode(), objectError.getDefaultMessage(),
                        objectError.getArguments());
                if (!StringUtils.isEmpty(message)) {
                    errorMsg.append(message + "<br />");
                }
            }
        }
        return errorMsg.toString();
    }


    /**
     * 表单检验
     *
     * @param duplicateValid
     * @param request
     * @return
     */
    @RequestMapping(value = "validate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            valid = baseService.doValid(duplicateValid);

            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            logger.error("验证异常", e);
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }

    /**
     * @param result
     * @return
     * @throws Exception
     */
    protected List<Map<String, Object>> getResultMap(List<?> result) throws Exception {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (result == null || result.size() == 0) {
            return mapList;
        }
        for (Object bean : result) {
            Map<String, Object> map = new HashMap<String, Object>(16);
            PropertyDescriptor[] pd = PropertyUtils.getPropertyDescriptors(bean);
            for (PropertyDescriptor pdp : pd) {
                if ("class".equals(pdp.getName())) {
                    continue;
                }
                map.put(pdp.getName(), pdp.getReadMethod().invoke(bean, new Object[0]));
            }
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 遍历类中的所有属性及赋值到报告模板中
     *
     * @param o      实体类
     * @param tag    模板内容
     * @param prefix 前缀
     * @return
     */
    @Override
    public String reflect(Object o, String tag, String prefix) {
     /*   if (StringUtils.isNotEmpty(prefix)) {
            prefix += ".";
        }*/
        //获取参数类
        Class cls = o.getClass();
        //将参数类转换为对应属性数量的Field类型数组（即该类有多少个属性字段 N 转换后的数组长度即为 N）
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            try {
                Object oo = f.get(o);
                String propertyTypeName = String.valueOf(f.getGenericType()).replace("class", "").trim();
                String value = "";
                if (oo != null) {
                    if (propertyTypeName.equals(int.class.getName())
                            || propertyTypeName.equals(Integer.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(long.class.getName())
                            || propertyTypeName.equals(Long.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(double.class.getName())
                            || propertyTypeName.equals(Double.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(float.class.getName())
                            || propertyTypeName.equals(Float.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(byte.class.getName())
                            || propertyTypeName.equals(Byte.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(short.class.getName())
                            || propertyTypeName.equals(Short.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(char[].class.getName())
                            || propertyTypeName.equals(Character[].class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(boolean.class.getName())
                            || propertyTypeName.equals(Boolean.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(String.class.getName())) {
                        value = String.valueOf(oo);
                    } else if (propertyTypeName.equals(java.util.Date.class.getName())) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = sdf.format(oo);
                    } else if (propertyTypeName.indexOf(List.class.getName()) > -1) {
                        Document doc = Jsoup.parse(tag);
                        Elements table = doc.select("table[name=" + f.getName() + "]");
                        List<Object> list = (List<Object>) oo;
                        for (Object obj : list) {
                            Field[] detailFields = obj.getClass().getDeclaredFields();
                            String tr = table.select("tr").get(1).outerHtml();
                            for (int j = 0; j < detailFields.length; j++) {
                                Field detailField = detailFields[j];
                                detailField.setAccessible(true);
                                Object detailOo = detailField.get(obj);
                                if (detailOo != null) {
                                    tr = tr.replaceAll(prefix + detailField.getName(), String.valueOf(detailOo));
                                }
                            }
                            value += tr;
                        }
                        table.select("tr").get(1).remove();
                        table.append(value);
                        tag = doc.outerHtml();
                        continue;
                    }

                }
                tag = tag.replaceAll(prefix + "." + f.getName()+"#", value);
                //f.getName()得到对应字段的属性名，f.get(o)得到对应字段属性值,f.getGenericType()得到对应字段的类型
                System.out.println("属性名：" + f.getName() + "；属性值：" + f.get(o) + ":" + String.valueOf(f.get(o)) + ";字段类型：" + f.getGenericType());
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return tag;
    }

    /**
     * 模版赋值
     *
     * @param o
     * @param tag
     * @return
     */
    @Override
    public String reflect2(Object o, String tag) {
        Document doc = Jsoup.parse(tag);
        Elements input = doc.getElementsByTag("input");
        Elements table = doc.getElementsByTag("table");
        Elements img = doc.getElementsByTag("img");
        try {
            Class cls = o.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (Element element : input) {
                String name = element.attr("name");
                if ("text".equals(element.attr("type"))) {
                    Field field = o.getClass().getDeclaredField(name);
                    field.setAccessible(true);
                    Object value = field.get(o);
                    element.tagName("span");
                    element.text(ConvertUtil.null2String(value));
                }
                if ("hidden".equals(element.attr("type"))) {
                    Field field = o.getClass().getDeclaredField(name);
                    field.setAccessible(true);
                    Object value = field.get(o);
                    element.tagName("span");
                    element.text(ConvertUtil.null2String(value));
                }
                if ("checkbox".equals(element.attr("type"))) {
                    Field field = o.getClass().getDeclaredField(name);
                    field.setAccessible(true);
                    String value = ConvertUtil.null2String(field.get(o));
                    if (value.equals(element.attr("value"))) {
                        element.attr("checked", true);
                    }
                }
            }
            for (Element element : table) {
                String name = element.attr("name");
                if (StringUtils.isNotEmpty(name)) {
                    Field field = o.getClass().getDeclaredField(name);
                    field.setAccessible(true);
                    List<Object> list = (List<Object>) field.get(o);
                    for (Object obj : list) {
                        Field[] detailFields = obj.getClass().getDeclaredFields();
                        String tr = element.select("tr").get(1).outerHtml();
                        for (int j = 0; j < detailFields.length; j++) {
                            Field detailField = detailFields[j];
                            detailField.setAccessible(true);
                            Object detailOo = detailField.get(obj);
                            if (detailOo != null) {
                                tr = tr.replaceAll(detailField.getName(), ConvertUtil.null2String(detailOo));
                            }
                        }
                        element.append(tr);
                    }
                    element.select("tr").get(1).remove();
                }
            }
            for(Element element : img) {
                String src = element.attr("src");
                String name = element.attr("name");
                if (StringUtils.isNotEmpty(name)) {
                    Field field = o.getClass().getDeclaredField(name);
                    field.setAccessible(true);
                    String value =ConvertUtil.null2String(field.get(o));
                    src = src.replaceAll("#"+field.getName(), value);
                }
                element.attr("src", src);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc.outerHtml();
    }

    @RequestMapping(value = "/GetImg*", method = RequestMethod.GET)
    @Override
    public void getImg(HttpServletRequest request, HttpServletResponse response) {
        String barcode = ConvertUtil.null2String(request.getParameter("barcode"));
        OutputStream os = null;
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            buffer = ReportGenerateUtil.create128CodeImg(barcode);
            response.getOutputStream().write(buffer);
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
